const mongoose = require('mongoose');
const { Schema } = mongoose;
mongoose.connect('mongodb://localhost:27017/experiencemanager', { useNewUrlParser: true, useUnifiedTopology: true });
const ComSchema = new Schema({
    commentId:{type:Number},
    expId:{type:Number},
    userAccount:{type:Number },

    commentContent: { details: { type: String }, date: { type: Date, default: Date.now } },//对插入这个对象的每一项对象数据的约束条件

});

const Com = mongoose.model('Com', ComSchema);


//发布评论方法
exports.releaseComment=function (comment,callback) {
    function search(){
        let random=Math.round(Math.random()*10000000000)
        Com.find({
            commentId:random
        }, function (err, res) {
            if (err) {
                callback({info:"发布失败"})
            }
            else {
                if (res.length == 0) {
                    const com = new Com({
                        commentId:random,
                        userAccount:comment.userAccount,
                        expId:comment.expId,
                        userName:comment.userName,
                        commentContent:{details:comment.content},

                    })
                    com.save().then(() => {
                        callback({info:{
                                commentId:random,
                                userAccount:comment.userAccount,
                                expId:comment.expId,
                                userName:comment.userName,
                                commentContent:{details:comment.content},
                            }})
                    });
                }
                else {
                    search()
                }
            }
        })
    }
    search()
}


//根据发布文章的id查找对应的所有评论
exports.findComment=function (expId,callback) {
    Com.find({
        expId
    },function (err,res) {
        if(err){
            callback({info:"查找失败"})
        }
        else{
            callback({info:"查找成功",res})
        }
    })
}

//根据评论id删除对应评论
exports.deleteComment = function (commentId, callback) {
    Com.remove({
        commentId
    }, function (err, ret) {
        if (err) {
            console.log({info: '删除失败'})
        }
        else {
            callback({info:"删除成功",ret})
        }
    })

}

//根据用户的id查找该用户的评论数
exports.findUserComment=function (userAccount,callback) {
    Com.find({
        userAccount
    },function (err,res) {
        if(err){
            callback({info:"查找失败"})
        }
        else{
            callback({info:"查找成功",res})
        }
    })
}